package com.rentalHome.controller;

import com.rentalHome.domain.Payment;
import com.rentalHome.domain.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import com.rentalHome.domain.User;
import com.rentalHome.repository.RoomRepository;
import com.rentalHome.repository.UserRepository;

/**
 *
 * @author LeeXyan
 * @date 2017年2月4日 下午2:54:08
 *
 **/

@RestController
@RequestMapping("/room")
public class RoomController {

	@Autowired
	private RoomRepository roomRepository;
	
	@Autowired
	private UserRepository userRepository;
	

	@GetMapping("/list")
	public ResponseEntity roomList(@RequestParam("userId")Long userId){
		User user=userRepository.findOne(userId);
		return ResponseEntity.ok(roomRepository.findByUser(user));
	}

	/*@PostMapping("/add")
	public ResponseEntity roomAdd(@RequestParam("userId")Long userId,
								  @RequestParam("name")String name,
								  @RequestParam("info")String info,
								  @RequestParam("isEmpty")Boolean isEmpty){
		Room room=new Room();
		User user=userRepository.findOne(userId);
		Room isRoom=roomRepository.findByNameAndIsEmpty(user,name,isEmpty);
		Payment payment=new Payment();
		payment.setType("1");
		Room rm;
		if(isRoom!=null){
			isRoom.setInfo(info);
			rm=roomRepository.save(isRoom);
		}else{
			room.setUser(user);
			room.setName(name);
			room.setIsEmpty(isEmpty);
			room.setInfo(info);
			*//*room.setPayments(payment);*//*
			rm=roomRepository.save(room);
		}

		return ResponseEntity.ok(rm);
	}*/

	@PostMapping("/add")
	public ResponseEntity roomAdd(@RequestParam("userId")Long userId,
								  @RequestParam("name")String name,
								  @RequestParam("info")String info){
		User user=userRepository.findOne(userId);
		Room room=new Room();
		room.setName(name);
		room.setInfo(info);
        room.setUser(user);
        room.setIsEmpty(true);
		return ResponseEntity.ok(roomRepository.save(room));
	}

	@GetMapping("/search")
	public ResponseEntity roomAdd(@RequestParam("name")String name){
		return ResponseEntity.ok(roomRepository.findByNames(name));
	}

	@GetMapping("/delete")
	public ResponseEntity roomDelete(@RequestParam("name")String name/*, @RequestParam("info")String info, @RequestParam("isEmpty")Boolean isEmpty*/){
		roomRepository.delete(roomRepository.findByName(name).getId());
		return ResponseEntity.ok("ok");
	}

	@GetMapping("/edit")
	public ResponseEntity roomEdit(@RequestParam("name")String name,
								   @RequestParam("info")String info){
		Room room=roomRepository.findByName(name);
		room.setInfo(info);
		roomRepository.save(room);
		return ResponseEntity.ok("ok");
	}
}
